package com.wxdc.nmgyt.nmgytwydc.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CodeBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.CodeBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.UserLoginResultBean;
import com.wxdc.nmgyt.nmgytwydc.presenter.LoginPersenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.LoginContract;
import com.wxdc.nmgyt.nmgytwydc.utils.FileUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2018/3/23.
 */

public class LoginActivity extends BaseActivity<LoginPersenter> implements LoginContract.View {
    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.login_username)
    EditText mLoginUsername;
    @BindView(R.id.login_pwd)
    EditText mLoginPwd;
    @BindView(R.id.login_remember_checkbox)
    CheckBox mLoginRememberCheckbox;
    @BindView(R.id.bt_username_clear)
    Button mBtUsernameClear;
    @BindView(R.id.bt_pwd_eye)
    Button mBtPwdEye;
    @BindView(R.id.login_guest_checkbox)
    CheckBox mLoginGuestCheckbox;
    private MyApp mApp;
    RxPermissions rxPermissions;
    @BindView(R.id.login_but01)
    Button mLoginBut01;
    private String userNameStr, userPwdStr;

    @Override
    protected int getLayout() {
        /*加载布局*/
        return R.layout.activity_login;

    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        rxPermissions = new RxPermissions(this);
        requestPermissions();
        mApp = MyApp.getInstance();
        if (!SharedPreferenceUtil.getUsername().equals("")) {
            mLoginRememberCheckbox.setChecked(true);
            mLoginUsername.setText(SharedPreferenceUtil.getUsername());
            mLoginPwd.setText(SharedPreferenceUtil.getPassword());
            mBtUsernameClear.setVisibility(View.VISIBLE);
        }
        mLoginUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                Log.i(TAG, "beforeTextChanged: ----------");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("".equals(s.toString())) {
                    mBtUsernameClear.setVisibility(View.INVISIBLE);
                } else {
                    mBtUsernameClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals(SharedPreferenceUtil.getUsername())) {
                    mLoginPwd.setText(SharedPreferenceUtil.getPassword());
                } else {
                    mLoginPwd.setText("");
                }
            }
        });

    }

    private void requestPermissions() {
        rxPermissions.requestEach(
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            FileUtil.createImageFolder();
                            FileUtil.createLayerFolder();
                            FileUtil.createGpsDatarFolder();
                            FileUtil.createPicImageFolder();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框

                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                        }
                    }
                });


    }

    private boolean isOpen = false;

    @OnClick({R.id.login_but01, R.id.bt_username_clear, R.id.bt_pwd_eye})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_but01:
                requestPermissions();
                userNameStr = mLoginUsername.getText().toString().trim();
                userPwdStr = mLoginPwd.getText().toString().trim();
                if (mLoginGuestCheckbox.isChecked()) {//无网络状态下使用游客登录
                    SharedPreferenceUtil.setToken("");
                    SharedPreferenceUtil.setSid("");
                    SharedPreferenceUtil.setGzdwdm("");
                    MainActivity.start(this);
                    finish();
                    return;
                }
                if (!Network.isConnected(mContext)) {
                    mApp.showToastLongMessage(mContext, getResources().getString(R.string.no_network));
                    return;
                }
                if ("".equals(userNameStr)) {
                    mApp.showToastLongMessage(mContext, "用户名不能为空");
                    mLoginUsername.requestFocus();//获取焦点 光标出现
                    return;
                } else if ("".equals(userPwdStr)) {
                    mApp.showToastLongMessage(mContext, "密码不能为空");
                    mLoginPwd.requestFocus();//获取焦点 光标出现
                    return;
                }
                showProgressDialog("登录中...");
                mPersenter.loginServer(userNameStr, userPwdStr);
                break;
            case R.id.bt_username_clear:
                mLoginUsername.setText("");
                SharedPreferenceUtil.setUsername("");
                SharedPreferenceUtil.setPassword("");
                mLoginUsername.requestFocus();
                mLoginRememberCheckbox.setChecked(false);
                break;
            case R.id.bt_pwd_eye:
                // 密码可见与不可见的切换
                if (isOpen) {
                    isOpen = false;
                } else {
                    isOpen = true;
                }
                // 默认isOpen是false,密码不可见
                changePwdOpenOrClose(isOpen);
                break;
        }
    }

    /**
     * 密码可见与不可见的切换
     *
     * @param flag
     */
    private void changePwdOpenOrClose(boolean flag) {
        // 第一次过来是false，密码不可见
        if (flag) {
            // 密码可见
            mBtPwdEye.setBackgroundResource(R.drawable.password_open);
            // 设置EditText的密码可见
            mLoginPwd.setTransformationMethod(HideReturnsTransformationMethod
                    .getInstance());
        } else {
            // 密码不接见
            mBtPwdEye.setBackgroundResource(R.drawable.password_close);
            // 设置EditText的密码隐藏
            mLoginPwd.setTransformationMethod(PasswordTransformationMethod
                    .getInstance());
        }
    }

    //=========================================================================================
    @Override
    public void loginResult(UserLoginResultBean bean) {
        hideProgressDialog();
        if (bean != null && "200".equals(bean.getCode())) {
           /* LogUtil.i("loginResult: ----code----->" + bean.getCode());
            LogUtil.i("loginResult: ----jwt----->" + bean.getJwt());
            LogUtil.i("loginResult: ----remessage----->" + bean.getReMessage());
            LogUtil.i("loginResult: ----sid----->" + bean.getSid());*/
            SharedPreferenceUtil.setToken(bean.getJwt());//保存Token
            SharedPreferenceUtil.setSid(bean.getSid());//保存Sid用来查询用户权限
            if (mLoginRememberCheckbox.isChecked()) {
                SharedPreferenceUtil.setUsername(userNameStr);
                SharedPreferenceUtil.setPassword(userPwdStr);
            }
            MainActivity.start(this);
            finish();
        } else {
            MyApp.getInstance().showToastLongMessage(mContext, "登录失败");
        }
    }

    @Override
    public void showError(String msg) {
        mApp.showToastLongMessage(this, msg);
        hideProgressDialog();
    }

    /*
   * 设置服务器IP地址
   * */
    private int clicks = 0;
    private long firstClickTime = 0;
    private AlertDialog mDialog;

    public void showSetIpDialog(View view) {
        clicks++;
        if (clicks == 1) {
            firstClickTime = System.currentTimeMillis();
        }
        if (System.currentTimeMillis() - firstClickTime >= 2 * 1000) {
            clicks = 0;
        }
        if (clicks == 5) {//显示对话框，修改ip地址
            showDialog();
        }
        Log.i(TAG, "showSetIpDialog: ------" + clicks + "------" + firstClickTime + "----------" + (System.currentTimeMillis() - firstClickTime));
    }

    private AlertDialog defineSetIpDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.set_ip_dialog, null);
        final EditText editText = (EditText) view.findViewById(R.id.ip_address_editxt);
        editText.setText(SharedPreferenceUtil.getHttp());//显示当前服务器IP地址
        builder.setView(view);
        builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferenceUtil.setHttp(editText.getText().toString().trim());
                Toast.makeText(LoginActivity.this, "服务器地址修改成功", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                finish();
                System.exit(0);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        return builder.create();
    }

    private void showDialog() {
        if (null == mDialog) {
            mDialog = defineSetIpDialog();
        }
        mDialog.setCanceledOnTouchOutside(false);//点击外部是否消失
        mDialog.show();
    }

    private void closeDialog() {
        if (null != mDialog) {
            mDialog.dismiss();
        }
    }
    public static void start(Context context){
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog();
    }
}
